package org.eclipseuseradmin.internal.ui.wizards;

import org.eclipse.core.runtime.Platform;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.INewWizard;
import org.eclipseuseradmin.internal.ui.UserAdminUiPlugin;
import org.eclipseuseradmin.ui.BaseRoleElementAdapter;
import org.eclipseuseradmin.ui.IGroup;
import org.eclipseuseradmin.ui.IRoleElement;
import org.eclipseuseradmin.ui.wizards.BaseNewRoleElementWizard;
import org.eclipseuseradmin.ui.wizards.NewRoleElementWizardPage;
import org.osgi.service.useradmin.Group;
import org.osgi.service.useradmin.Role;

public class NewGroupWizard extends BaseNewRoleElementWizard implements INewWizard {

	@Override
	public void addPages() {

		addPage(new NewRoleElementWizardPage("main",
				WizardsMessages.get().NewGroupWizard_pageTitle, WizardsMessages
						.get().NewGroupWizard_pageDescription, UserAdminUiPlugin
						.getImageDescriptor("/icons/group_wiz.gif")));
	}

	@Override
	public boolean performFinish() {

		Group group = (Group) getUserAdmin().createRole(getModel().getName(),
				Role.GROUP);

		IGroup adapter = (IGroup) getAdapterManager().getAdapter(
				group, IGroup.class);

		adapter.setObjectClass("group");
		adapter.setOrganizationUnit("groups");

		IStructuredSelection selection = getSelection();
		Object parent = selection.getFirstElement();
		if (parent != null && parent instanceof Role) {
			IRoleElement roleElement = BaseRoleElementAdapter
					.adapt((Role) parent);
			if (roleElement != null && roleElement.acceptChild(group)) {

				roleElement.addChild(group);
				adapter.addParent((Group) parent);
			}

		}

		selectAndReveal(group);

		return true;
	}
}
